package design.pattern.Lu14IteratorPattern;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @program JavaBase
 * @description: 迭代器模式
 * @author: zhanglu
 * @create: 2020-04-09 18:01:00
 */
public class IteratorPattern02 {

    public static void main(String[] args) {

        Aggregate aggregate = new ConcreteAggregate();

        aggregate.add("a");
        aggregate.add("b");
        aggregate.add("c");

        MyIterator iterator = aggregate.iterator();
        while (iterator.hasNext()){
            ConcreteAggregate next = (ConcreteAggregate) iterator.next();
            System.out.println(next.todo());
        }


    }

}

interface MyIterator{

    Object next();
    boolean hasNext();
    boolean remove();

}

class ConcreteIterator implements MyIterator{

    private List ls = new CopyOnWriteArrayList();
    private int currentCount = 0;

    public ConcreteIterator(List ls){
        this.ls = ls;
    }

    @Override
    public Object next() {
        return this.ls.get(currentCount++);
    }

    @Override
    public boolean hasNext() {
        return this.currentCount < this.ls.size();
    }

    @Override
    public boolean remove() {
        boolean flag = true;
        try {
            this.ls.remove(currentCount++);
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }
}

interface Aggregate{
    void add(String name);
    String todo();
    MyIterator iterator();
}

class ConcreteAggregate implements Aggregate{

    private List<Object> ls = new CopyOnWriteArrayList();
    private String name;

    public ConcreteAggregate(){}

    public ConcreteAggregate(String name){
        this.name = name;
    }

    @Override
    public void add(String name) {
        this.ls.add(new ConcreteAggregate(name));
    }

    @Override
    public String todo() {
        return "操作：" + this.name;
    }

    @Override
    public MyIterator iterator() {
        return new ConcreteIterator(this.ls);
    }
}
